

#include "lmexxx_conf.h"

#define DELAY_SEND_BUFF_SIZE		16
#define DELAY_TIME_TICK_MS			100

typedef struct{
	uint8_t* msg;
	uint16_t msg_len;
	uint16_t delay_time_tick;
}DELAY_SEND_ITEM_STRUCT;

static DELAY_SEND_ITEM_STRUCT delay_send_buff[DELAY_SEND_BUFF_SIZE];
static uint8_t delay_send_timer = 0xff;

extern void delay_send_send_hook(uint8_t* msg, uint16_t msg_len);

uint8_t delay_send_send(uint8_t* msg, uint16_t msg_len, uint16_t delay_time_tick)
{
	if(delay_time_tick == 0){
		delay_send_send_hook(msg, msg_len);
		return 1;
	}
	for(uint8_t i = 0; i < DELAY_SEND_BUFF_SIZE; i++){
		if(0 == delay_send_buff[i].delay_time_tick){
			delay_send_buff[i].msg = msg;
			delay_send_buff[i].msg_len = msg_len;
			delay_send_buff[i].delay_time_tick = delay_time_tick;
			if(0 == APP_CheckGenTimerRunning(delay_send_timer)){
				APP_StartGenTimer(delay_send_timer);
			}
			return 1;
		}
	}
	return 0;
}

static void delay_send_timer_handler(void)
{
	uint8_t empty = 1;
	for(uint8_t i = 0; i < DELAY_SEND_BUFF_SIZE; i++){
		if(delay_send_buff[i].delay_time_tick > 0){
			empty = 0;
			delay_send_buff[i].delay_time_tick--;
			if(delay_send_buff[i].delay_time_tick == 0){
				delay_send_send_hook(delay_send_buff[i].msg, delay_send_buff[i].msg_len);
			}
		}
	}
	if(empty){
		APP_StopGenTimer(delay_send_timer);
	}
}

uint8_t delay_send_init(void)
{
	if(delay_send_timer == 0xff){
		delay_send_timer = APP_NewGenTimer(DELAY_TIME_TICK_MS, delay_send_timer_handler);
		if(delay_send_timer == 0xff){
			return 0;
		}
	}

	for(uint8_t i = 0; i < DELAY_SEND_BUFF_SIZE; i++){
		delay_send_buff[i].delay_time_tick = 0;
	}
	return 1;
}
